package com.xiaocg.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadInterruptDemo {

    static volatile boolean isStop=false;
    static AtomicBoolean isStop2 = new AtomicBoolean(false);
    public static void main(String[] args) throws Exception {
        //volatileStop();
        threadInterrupted();
    }

    private static void threadInterrupted() throws Exception {
        Thread thread = new Thread(()->{
            while (true){
                boolean interrupted = Thread.currentThread().isInterrupted();
                if (interrupted){
                    System.out.println("----------停止");
                    break;
                }

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); //在sleep wait,join 期间调用了
                    e.printStackTrace();
                }

                System.out.println("-----------volatile t1 ");
            }
        },"interrupted t1");

        thread.start();
        TimeUnit.MILLISECONDS.sleep(500);

        new Thread(()->{
            thread.interrupt();
        },"t2").start();

    }

    private static void volatileStop() {
        new Thread(()->{
            while (true){
                if (isStop){
                    System.out.println("----------停止");
                    break;
                }
                System.out.println("-----------volatile");
            }
        },"t1").start();

        new Thread(()->{
            isStop = true;
        },"t2").start();
    }


}
